package com.william.jdbcplus.core.util;

import com.william.jdbcplus.core.enums.SqlMethod;
import com.william.jdbcplus.core.metadata.TableHelperUtil;
import com.william.jdbcplus.common.entity.Entity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * 增删改查通用类
 *
 * @author willieni
 */
public class CrudUtil {

    public static <M extends Entity> int copyList(List<M> entityList, DataSource ds) {
        if (entityList == null || entityList.size() == 0) {
            return 0;
        }

        int max = 1000;
        SqlMethod sqlMethod = SqlMethod.INSERT_LIST;
        M entity = entityList.get(0);
        Class<?> clazz = entity.getClass();
        String tableName = TableHelperUtil.getTableName(clazz);
        String columnInsert = TableHelperUtil.getColumnInsert(clazz);
        String valuesInsert = TableHelperUtil.getValuesInsert(clazz);
        String sql = String.format(sqlMethod.getSql(), tableName, columnInsert, valuesInsert);
        NamedParameterJdbcTemplate jdbcOpt = getTemplate(ds);
        for (int fromIndex = 0; fromIndex < entityList.size(); fromIndex = fromIndex + max) {
            int toIndex = fromIndex + max;
            if (toIndex > entityList.size()) {
                toIndex = entityList.size();
            }

            List<M> rows = entityList.subList(fromIndex, toIndex);
            //对象转 MAP 列表
            List<Map<String, Object>> rowMap = TableHelperUtil.getEntityAttrMapList(rows);
            SqlParameterSource[] batchValues = SqlParameterSourceUtils.createBatch(rowMap);
            jdbcOpt.batchUpdate(sql, batchValues);
        }

        return entityList.size();
    }

    private static NamedParameterJdbcTemplate getTemplate(DataSource ds) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
        return namedParameterJdbcTemplate;
    }
}
